package com.yangjiayu.iot.system.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yangjiayu.iot.system.mapper.SysUserMapper;
import com.yangjiayu.iot.system.pojo.SysUser;
import com.yangjiayu.iot.system.query.SysUserQuery;
import com.yangjiayu.iot.system.service.SysUserService;
import com.yangjiayu.iot.web.execption.GuiguException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 系统用户相关接口的实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public Page<SysUser> findSysUserByQuery(Integer page,
        Integer size,
        SysUserQuery sysUserQuery) {
        return sysUserMapper.pageSysUserByQuery(new Page<>(page,size),
            sysUserQuery);
    }

    /**
     * 查询用户的详细信息
     * @param id
     * @return
     */
    @Override
    public SysUser findOne(Long id) {
        return sysUserMapper.selectById(id);
    }

    /**
     * 新增用户
     *
     * @param sysUser
     */
    @Override
//    @Transactional(rollbackFor = Exception.class)//只要出异常就会滚
    public void save(SysUser sysUser) {
        //获取新增用户的明文密码
        String password = sysUser.getPassword();
        //将明文转换为密文存储到数据库中去  MD5有风险 BCrypt 加密后都不一样 校验也必须使用配套的checkpw(明文，密文)
        String hashpw = BCrypt.hashpw(password);
        //替换 数据库密码的字段要改大一点
        sysUser.setPassword(hashpw);
        //保存用户的数据
        int insert = sysUserMapper.insert(sysUser);
        if(insert <= 0){
            throw new GuiguException(201, "新增用户失败!");
        }
    }

    /**
     * 修改用户: 不允许修改密码,修改密码单独的功能!!!
     *
     * @param sysUser
     */
    @Override
    public void update(SysUser sysUser) {
        //修改用户信息
        int i = sysUserMapper.updateById(sysUser);
        if(i <= 0){
            throw new GuiguException(201, "修改用户的信息失败!");
        }
    }

    /**
     * 删除用户
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        //删除用户
        int i = sysUserMapper.deleteById(id);
        if(i < 0){
            throw new GuiguException(201, "删除用户失败!");
        }
    }
}
